//
//  DJShopViewController.m
//  Adorable_Things
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "DJShopViewController.h"
#import "DJCommentListModel.h"
#import "DJShopListView.h"
#import "DJShopListHeaderCollectionReusableView.h"
#import "DJAttentionCollectionViewCell.h"
#import "UMSocial.h"
#import "ATMainDetailViewController.h"
#import "DJSearchViewController.h"
#import "ATLoginViewController.h"

#define kShopUrl @"http://api.menghuoapp.com/v1/shop/detail"
#define kListUrl @"http://api.menghuoapp.com/v1/shop/item_list"
#define kmarkUrl @"http://api.menghuoapp.com/v1/item/mark"
#define kUnMarkUrl @"http://api.menghuoapp.com/v1/item/unmark"
#define kCommentUnMarkUrl @"http://api.menghuoapp.com/v1/shop/unmark"
#define kCommentmarkUrl @"http://api.menghuoapp.com/v1/shop/mark"


@interface DJShopViewController () <UICollectionViewDataSource, UICollectionViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *listArr;
@property (nonatomic, strong) NSString *order_by;
@property (nonatomic, strong) NSString *free_ship;

@property (nonatomic, strong) DJShopListView *listV;
@property (nonatomic, strong) NSString *logo;
@property (nonatomic, strong) NSString *intro;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *followed;
@property (nonatomic, strong) NSNumber *favorite;
@property (nonatomic, strong) NSNumber *total_item;

@property (nonatomic, assign) NSInteger index; // 关注 0-加关注 1-已关注

@end

@implementation DJShopViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor orangeColor];
    
    
    
    self.free_ship = @"0";
    self.order_by = @"3";
    
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(10, 20, 20, 20);
    [backButton setImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:(UIControlStateNormal)];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *shareBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    shareBut.frame = CGRectMake(kWidth - 30, 20, 20, 20);
    [shareBut setImage:[UIImage imageNamed:@"iconfont-fenxiang-2"] forState:(UIControlStateNormal)];
    [shareBut addTarget:self action:@selector(shareButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:backButton];
    [self.view addSubview:shareBut];
    

    UIButton *searchBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    searchBut.frame = CGRectMake((kWidth - 150)/2, 20, 150,20);
    searchBut.backgroundColor = [UIColor whiteColor];
    searchBut.layer.cornerRadius = 10;
    searchBut.layer.masksToBounds = YES;
    searchBut.imageEdgeInsets = UIEdgeInsetsMake(0, 65, 0, 65);
    [searchBut setImage:[UIImage imageNamed:@"iconfont-sousuo"] forState:(UIControlStateNormal)];
    [searchBut addTarget:self action:@selector(searchAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:searchBut];
    
    self.listV = [[DJShopListView alloc]initWithFrame:CGRectMake(0, 42, kWidth, kHeight - 42)];
    [self.view addSubview:self.listV];
    
    [self setupdata];
    [self addSubView];
}

- (void)setupdata
{
    ATUserManager *userManager = [ATUserManager shareManager];
   
    NSDictionary *parDic = @{@"shop_id":self.shop_id,@"auth_token": userManager.auth_token};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:kShopUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dataDic = responseObject[@"data"];
        self.logo = dataDic[@"logo"];
        self.name = dataDic[@"name"];
        self.followed = dataDic[@"followed"];
        self.total_item = dataDic[@"total_item"];
        self.intro = dataDic[@"intro"];
        self.favorite = dataDic[@"favorite"];
        
        self.listBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    /*
     热销 page_size=20&order_dir=1&shop_id=153&page=0&order_by=3&
     最新 page_size=20&order_dir=1&shop_id=153&page=0&order_by=1&
     价格 page_size=20&order_dir=1&shop_id=153&page=0&order_by=2&
     包邮 page_size=20&free_ship=1&order_dir=1&shop_id=153&page=0&order_by=1&
     
     */
    NSDictionary *par = nil;
    if ([self.free_ship isEqualToString:@"0"]) {
        par = @{@"shop_id":self.shop_id,@"page_size":@"20",@"order_dir":@"1",@"page":@"0",@"order_by":self.order_by};
    }else{
        par = @{@"shop_id":self.shop_id,@"page_size":@"20",@"order_dir":@"1",@"page":@"0",@"order_by":@"1",@"free_ship":@"1"};
    }
    
    [manager POST:kListUrl parameters:par progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.listArr = [NSMutableArray array];
        NSArray *dataArr = responseObject[@"data"];
        for (NSDictionary *oneDic in dataArr) {
            DJCommentListModel *model = [[DJCommentListModel alloc]init];
            [model setValuesForKeysWithDictionary:oneDic];
            [self.listArr addObject:model];
        }
        
        
        [self.listV.collectionV reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)addSubView
{
    
    self.listV.collectionV.delegate = self;
    self.listV.collectionV. dataSource = self;
    // 滚动
    self.listV.delegate = self;
    self.listV.collectionV.scrollEnabled = NO;
    
    [self.listV.attentionButton addTarget:self action:@selector(attentionAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.listV.collectionV registerNib:[UINib nibWithNibName:@"DJAttentionCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"AttentionCollectionCell"];
    
    [ self.listV.collectionV registerClass:[DJShopListHeaderCollectionReusableView class]forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ShopListCollectionHeader"];
    
    
    __weak DJShopViewController *shopVC = self;
    self.listBlock = ^void(){
        [shopVC.listV.iconImageV sd_setImageWithURL:[NSURL URLWithString:shopVC.logo]];
        shopVC.listV.nameLab.text = shopVC.name;
        shopVC.listV.favoriteLab.text = [NSString stringWithFormat:@"粉丝数  %@  |  商品数  %@",shopVC.followed, shopVC.total_item];
        shopVC.listV.introLab.text = shopVC.intro;
        if ([shopVC.favorite integerValue] == 1) {
            [shopVC.listV.attentionButton setTitle:@"已关注" forState:(UIControlStateNormal)];
            shopVC.index = 1;
        }else{
            [shopVC.listV.attentionButton setTitle:@"关注" forState:(UIControlStateNormal)];
            shopVC.index = 0;
        }
    };
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    if (scrollView.contentOffset.y >= 220) {
        self.listV.contentOffset = CGPointMake(0, 220);
        self.listV.scrollEnabled = NO;
        self.listV.collectionV.scrollEnabled = YES;
    
    }
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        if (scrollView.contentOffset.y < 0) {
            self.listV.collectionV.scrollEnabled = NO;
            self.listV.scrollEnabled = YES;
        }
    }
    if (![scrollView isKindOfClass:[UICollectionView class]]) {
        if (scrollView.contentOffset.y < 210) {
            self.listV.collectionV.scrollEnabled = NO;
        }else{
            self.listV.collectionV.scrollEnabled = YES;
        }
    }
    if (self.listArr.count == 0) {
        self.listV.scrollEnabled = YES;
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.listArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DJAttentionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AttentionCollectionCell" forIndexPath:indexPath];
    
    DJCommentListModel *model = self.listArr[indexPath.row];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.pic_url]];
    cell.imageV.layer.cornerRadius = 5;
    cell.imageV.layer.masksToBounds = YES;
    cell.nameLab.text = model.title;
    cell.priceLab.text = [NSString stringWithFormat:@"￥%@", model.price];
    cell.Lab.text = [NSString stringWithFormat:@"人气%@",model.favorite_num];
    
    if ([model.favorite integerValue] == 0) {
        [cell.favoriteButton setImage:[UIImage imageNamed:@"iconfont-tubiao-2"] forState:(UIControlStateNormal)];
        cell.favoriteButton.tintColor = [UIColor whiteColor];
    }else{
        [cell.favoriteButton setImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
        cell.favoriteButton.tintColor = [UIColor redColor];
    }
    [cell.favoriteButton addTarget:self action:@selector(favoriteButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.favoriteButton.tag = 500 + indexPath.row;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DJCommentListModel *model = self.listArr[indexPath.row];
    ATMainDetailViewController *mainVC = [[ATMainDetailViewController alloc]init];
    mainVC.item_id = model.item_id;
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    mainVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mainVC animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    DJShopListHeaderCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ShopListCollectionHeader" forIndexPath:indexPath];
    headView.backgroundColor = [UIColor whiteColor];
    
    for (int i = 0; i < 4; i++) {
        UIButton *But = [headView viewWithTag:450 + i];
        [But addTarget:self action:@selector(headButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    
    return headView;
    
}

- (void)headButtonClick:(UIButton *)button
{
    for (int i = 0; i < 4; i++) {
        UIButton *But = [button.superview viewWithTag:450 + i];
        [But setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    }
    switch (button.tag) {
        case 450:
            self.order_by = @"3";
            self.free_ship = @"0";
            break;
        case 451:
            self.order_by = @"1";
            self.free_ship = @"0";
            break;
        case 452:
            self.order_by = @"2";
            self.free_ship = @"0";
            break;
        case 453:
            self.order_by = @"1";
            self.free_ship = @"1";
            break;
            
        default:
            break;
    }
    [button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
 //   UIImageView *imageV = [button.superview viewWithTag:button.tag - 10];
    
    [self setupdata];
}

// 关注按钮的点击事件
- (void)attentionAction:(UIButton *)button
{
    ATUserManager *userManager = [ATUserManager shareManager];
    
    NSDictionary *parDic = @{@"shop_id":self.shop_id,@"auth_token":userManager.auth_token};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    if (self.index == 1) {
        
        [manager POST:kCommentUnMarkUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self.listV.attentionButton setTitle:@"关注" forState:(UIControlStateNormal)];
            self.index = 0;
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }else{
        [manager POST:kCommentmarkUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [self.listV.attentionButton setTitle:@"已关注" forState:(UIControlStateNormal)];
            self.index = 1;
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
}

//图片上的喜欢按钮的点击事件
- (void)favoriteButtonClick:(UIButton *)button
{
    ATUserManager *userManager = [ATUserManager shareManager];
    if (userManager.isLogin == 0) {
        
        ATLoginViewController *loginVC = [[ATLoginViewController alloc]init];
        UINavigationController *loginNav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        loginNav.navigationBarHidden = YES;
        [self presentViewController:loginNav animated:YES completion:nil];
        
    }else{
        DJCommentListModel *model = self.listArr[button.tag - 500];
        DJAttentionCollectionViewCell *cell = (DJAttentionCollectionViewCell *)[self.listV.collectionV cellForItemAtIndexPath:[NSIndexPath indexPathForRow:button.tag - 500 inSection:0]];
        NSDictionary *parDic = @{@"item_id":model.item_id,@"auth_token":userManager.auth_token};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        if ([model.favorite integerValue] == 1) {
            
            [manager POST:kUnMarkUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [cell.favoriteButton setImage:[UIImage imageNamed:@"iconfont-tubiao-2"] forState:(UIControlStateNormal)];
                cell.favoriteButton.tintColor = [UIColor whiteColor];
                model.favorite = [NSNumber numberWithInt:0];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }else{
            
            [manager POST:kmarkUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [cell.favoriteButton setImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
                cell.favoriteButton.tintColor = [UIColor redColor];
                model.favorite = [NSNumber numberWithInt:1];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }

    }
    
}

// 分享按钮
- (void)shareButtonAction:(UIButton *)button
{
    // 友盟appkey:56971506e0f55abee6001622
    NSString *text = [NSString stringWithFormat:@"我在Adorable_Things关注了%@", self.name];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56971506e0f55abee6001622"
                                      shareText:text
                                     shareImage:self.listV.iconImageV.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,nil]
                                       delegate:nil];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
}

- (void)backAction:(UIButton *)button
{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)searchAction:(UIButton *)button
{
    DJSearchViewController *searchVC = [[DJSearchViewController alloc]init];
    searchVC.shop_id = self.shop_id;
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
